#include <iostream>
#include "EventLoopThread.h"
#include "EventLoop.h"
#include "Event.h"
#include "PipeEvent.h"
#include "Network.h"
#include <thread>

#include "Config.h"
#include "LogStream.h"
#include "Task.h"
#include "TaskMgr.h"
#include "TTime.h"
#include <stdio.h>
#include <iostream>
#include <memory>
#include"EventLoopThreadPool.h" //
#include "InetAddress.h"
#include "SocketOpt.h"


#include "Acceptor.h"

#include "TcpConnection.h"
#include "UdpSocket.h"

using namespace tmms::network;




EventLoopThread eventloop_thread;
std::thread th;



void TestEventLoopThread(){
    EventLoopThreadPool pool(2,0,2);

    pool.Start();
    std::cout<<"thread id :"<<std::this_thread::get_id()<<std::endl;

    std::vector<EventLoop* > list = pool.GetLoops();
    int i=0;
    for(auto &e:list)
    {
        e->RunInLoop([&e](){
            std::cout << "loop"<< e<<"thread id:"<<std::this_thread::get_id()<<std::endl;
        });
        std::cout<<"loop:"<<e<<std::endl;
    }

    // EventLoop * loop = pool.GetNextLoop();
    // std::cout<<"loop:"<<loop<<std::endl;
    // loop = pool.GetNextLoop();
    // std::cout<<"loop:"<<loop<<std::endl;

}


void TestInetaddress()
{
    std::string host;
    while(std::cin>>host)
    {
        InetAddress addr(host);
        std::cout<<"the host is:"<<addr.IP()<<"and the port is :"<<addr.Port()<<std::endl;    
    }
    return ;
}


int TestSocketClient(){
    int sock =SocketOpt::CreateNonblockingTcpSocket(AF_INET);
    if(sock<0)
    {
        std::cerr<<"socket failed.sock"<<sock<<"errno:" <<errno<<std::endl;
        return -1;
    }
    InetAddress server("127.0.0.1:23333");
    SocketOpt opt(sock);
    opt.SetNooBlocking(false);

    auto ret = opt.Connetct(server);

    if (ret < 0) {
    std::cerr << "Connect failed. errno: " << errno 
        << " (" << strerror(errno) << ")" << std::endl;
    }
    std::cout<<"connet ret :"<<ret<<std::endl
    <<"local:"<<opt.GetLocalAddr()->ToIpPort()
    <<"peer:"<<opt.GetPeerAddr()->ToIpPort()<<std::endl;
    return 0;
}

int TestSocketServer(){
    int sock =SocketOpt::CreateNonblockingTcpSocket(AF_INET);
    if(sock<0)
    {
        std::cerr<<"socket failed.sock"<<sock<<"errno:" <<errno<<std::endl;
        return -1;
    }
    InetAddress server("0.0.0.0:23333");
    SocketOpt opt(sock);
    opt.SetNooBlocking(false); //这个是阻塞模式
    opt.BindAddress(server);
    opt.Listen();
    InetAddress addr;
    auto ret = opt.Accept(&addr); // 由于是阻塞模式，所以他会
    std::cout<<"conAcceptnet ret :"<<ret<<std::endl
    <<"local:"<<addr.ToIpPort();
    return 0;
}



void TestAcceptor(){
    eventloop_thread.Run();//就是一个创建了一个线程
    EventLoop * loop = eventloop_thread.loop();
    if(loop){
        InetAddress server("0.0.0.0:23333");
        Acceptor acceptor(loop,server);
        acceptor.SetAcceptCallback([](int fd,const InetAddress &addr){ //连接完成的回调函数
            std::cout<<"host"<<addr.ToIpPort()<<std::endl;
        });
        acceptor.Open();
        while(1){
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    }
    return ;
}


void TestTcpConnection()
{
    eventloop_thread.Run(); //就tm一个线程
    EventLoop * loop = eventloop_thread.loop();
  
    if(loop){
        std::vector<TcpConnectionPtr> list; //连接列表
        InetAddress server("0.0.0.0:23333");
        auto acceptor = std::make_shared<Acceptor>(loop, server);

        acceptor->SetAcceptCallback([&list,&loop,&server](int fd,const InetAddress &addr){

            //收到连接之后，直接构造一个tcpconnection
            TcpConnectionPtr connection = std::make_shared<TcpConnection>(loop,fd,server,addr);//makeshared传的是构造函数的参数
           
             std::cout<<"write complete,wodetian a afa "<<std::endl;

            // 设置读回调
            connection->setRecvMsgCallback([](const TcpConnectionPtr&con,MsgBuffer &buf){
                std::cout << "recv msg :"<<buf.peekInt64()<< std::endl;
                //buf.RetrieveAll(); //这里本意是清理全部的信息
            });

             // 设置关闭回调（自动从列表移除）
            connection->SetWriteCompleteCallback([&loop](const TcpConnectionPtr& con){
                std::cout<<"write complete,host"<<con->GetPeerlAddr().ToIpPort()<<std::endl;
                loop->DelEvent(con);
                con->ForceClose();
            });

            // 加入事件循环
            loop->AddEvent(connection);
            list.push_back(connection);
        });

        
        acceptor->Start();//放到事件循环中而已
        std::cout<<"something wriong"<<std::endl;
        while(1){
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    }
    return ;
}



int main (){

    // TimingWheel wheel;
    // wheel.RunAfter(3,[](){
    //     std::cout<<"threed second task done "<<std::endl;
    // });

    // wheel.RunEvery(5,[](){
    //     std::cout<<"threed second task done "<<std::endl;
    // });

    // while (true) {

    //          // 使用TTime::NowMS()获取当前毫秒时间戳
    //     int64_t now_ms = tmms::base::TTime::NowMS();
    //     wheel.OnTimer(now_ms);  // 传入毫秒时间戳
        
    //     int64_t now = std::chrono::system_clock::now().time_since_epoch().count();
    //     wheel.OnTimer(now);
    //     sleep(1);
    // }


    //TestSocketServer();
   //TestSocketClient();

    TestTcpConnection();

    //TestAcceptor();

    return 0;
}